<?php
/**
 * Desc: Service模板
 * User: zdb
 * Date: 2023/6/5
 * Time: 11:22
 */

namespace app\api\service\user;
use app\api\service\clockin\ClockinActivityPlanTaskService;
use app\api\service\setting\ClockinReviewRuleService;
use app\util\DateUtil;
use think\facade\Db;

class UserClockinRecordService
{

    private $primaryTable;

    public function __construct()
    {
        $this->primaryTable = "yj_user_clockin_record";
    }

    public function findRowById($id)
    {
        return Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->find();
    }

    public function findRowByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        return Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->strict(false)
            ->find();
    }

    public function getListByManyId($arrId)
    {
        $list = Db::table($this->primaryTable)->alias('a')
            ->whereIn('id', $arrId)
            ->select()
            ->toArray();
        return $list;
    }

    public function assembleFilterCondition($data)
    {
        $condition = ['a.status > 0'];

        if (!empty($data['title'])) {
            $condition[] = "title like '%" . $data['title'] . "%'";
        }

        if (isset($data['plan_id'])) {
            $condition[] = "a.plan_id =".$data['plan_id'];
        }

        return empty($condition) ? "" : implode(" AND ", $condition);
    }

    public function getListNoPage($data = [])
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->select()
            ->toArray();
        return $res;
    }

    public function getListWithPage($data, $pageIndex = 1, $pageSize = 30)
    {
        $offset = ($pageIndex - 1) * $pageSize;
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->leftJoin("yj_user u", "u.id = a.user_id")
            ->where($condition)
            ->field("a.*, u.account, u.nickname")
            ->limit($offset, $pageSize)
            ->order('id desc')
            ->select();
        return $res;
    }

    public function getTotalNum($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $num = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->count();
        return $num;
    }

    public function createRow($data)
    {
        $data['status'] = isset($data['status']) ? $data['status']:1;
        $res = Db::table($this->primaryTable)
            ->duplicate(array('user_id', 'plan_id'))
            ->strict(false)
            ->insert($data, true);
        return $res;
    }

    public function createManyRow($data)
    {
        $res = Db::table($this->primaryTable)
            ->duplicate(array('user_id', 'plan_id'))
            ->strict(false)
            ->insertAll($data, true);
        return $res;
    }

    public function updateRowById($id, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByData($condition, $data)
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByManyId($arrId, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeRowById($id)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByManyId($arrId)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    /**
     * 打卡的同时，要加入温习记录表
     * @param $arrPlanId
     * @param $arrUserId
     * @return array|bool
     */
    public function createManyRowOneByOne($arrPlanId, $arrUserId)
    {
        $nowTime = DateUtil::getCurrentDatetime();

        $serviceReviewRule = new ClockinReviewRuleService();
        $firstPhaseInfo = $serviceReviewRule->getSystemFirstReviewRulePhaseInfo();
        $serviceUserReview = new UserClockinReviewService();
        Db::table($this->primaryTable)->startTrans();
        $failData = array();
        $count = 0;
        $planTaskService = new ClockinActivityPlanTaskService();
        foreach($arrPlanId as $planId){
            foreach($arrUserId as $userId){
                $addData = array(
                    'plan_id' => $planId,
                    'user_id' => $userId,
                    'is_clockin' => 1,
                    'status'  => 1,
                    'update_time' => $nowTime
                );
                $res1 = $this->createRow($addData);

                $listPlanTask = $planTaskService->getSimpleListNoPage(array('plan_id' => $planId));
                $arrPlanTaskId = array_column($listPlanTask, 'id');
                $addReviewData = array();
                foreach($arrPlanTaskId as $planTaskId){
                    $addReviewData[] = array(
                        'user_id' => $userId,
                        'plan_task_id' => $planTaskId,
                        'rule_phase_id' => $firstPhaseInfo['rule_phase_id'],
                        'show_time' => $firstPhaseInfo['review_start_time'],
                        'is_review' => 0
                    );
                }
                $res2 = $serviceUserReview->createManyRow($addReviewData);
                if($res1 && $res2){
                    $count++;
                }else{
                    $failData[] = $addData;
                }
            }
        }
        $total = count($arrPlanId) * count($arrUserId);
        if($count == $total){
            Db::table($this->primaryTable)->commit();
            return true;
        }else{
            Db::table($this->primaryTable)->rollback();
            return $failData;
        }
    }
}